<template>
  <el-dialog :visible.sync="verifyVisible" width="450px" :close-on-click-modal="false" @closed="reset">
    <div slot="title" class="dialog-title">账户安全验证</div>
    <el-form
      ref="changeForm"
      :model="changeForm"
      :rules="changeRules"
      label-position="top"
      size="medium"
      class="change-form"
      :hide-required-asterisk="true">
      <el-form-item prop="password">
        <span slot="label" class="form-item-label" :class="{ 'red-color': passError }">
          密码验证
          <span v-if="passError" style="font-size: 0.9285em">（密码错误）</span>
        </span>
        <el-input type="password" v-model="changeForm.password" placeholder="请输入当前账号密码" />
      </el-form-item>
      <el-form-item prop="authCode" v-if="user.phoneNumber != null && user.phoneNumber != ''">
        <span slot="label" class="form-item-label" :class="{ 'red-color': codeError }">
          <template v-if="type === 'phone'"> 短信验证（接收手机号 {{ user.phoneNumber | phoneFilter }}） </template>
          <template v-if="type === 'email'"> 邮箱验证（接收邮箱 {{ user.email | emailFilter }}） </template>
          <span v-if="codeError" style="font-size: 0.9285em">（验证码错误）</span>
        </span>
        <el-input v-model.number="changeForm.authCode" :placeholder="placeholder">
          <el-button slot="append" class="send-btn" @click="sendCode" :disabled="validateCodeBtn">{{
            validateCodeBtnText
          }}</el-button>
        </el-input>
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button @click="reset">取 消</el-button>
      <el-button type="primary" @click="netxtStep">下一步</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { checkPassword, checkCode } from "@/api/system/user"
import { sendPhoneCode, sendEmailCode } from "@/api/system/verifyCode"

export default {
  props: {
    user: {
      type: Object,
    },
  },
  filters: {
    phoneFilter(val) {
      let reg = /^(.{3}).*(.{4})$/
      return val.replace(reg, "$1****$2")
    },
    emailFilter(val) {
      let reg = /^(.{3}).*(.{6})$/
      return val.replace(reg, "$1****$2")
    },
  },
  data() {
    return {
      type: "",
      changeForm: {
        password: "",
        authCode: "",
      },
      placeholder: "",
      validateCodeBtn: false,
      validateCodeBtnText: "",
      passError: false,
      codeError: false,
      verifyVisible: false,
      changeRules: {
        password: [{ required: true, trigger: "blur", message: "请输入密码" }],
        authCode: [{ required: true, trigger: "blur", message: "请输入验证码" }],
      },
    }
  },
  methods: {
    doVerify(type) {
      if (type === "phone") {
        this.validateCodeBtnText = "发送短信验证码"
        this.placeholder = "请输入短信验证码"
      } else if (type === "email") {
        this.validateCodeBtnText = "发送邮箱验证码"
        this.placeholder = "请输入邮箱验证码"
      }
      this.type = type
      this.verifyVisible = true
    },
    sendCode() {
      this.$refs["changeForm"].validateField("password", (err) => {
        if (!err) {
          checkPassword({ password: this.changeForm.password }).then((res) => {
            if (res.data) {
              this.passError = false
              if (this.type === "phone") {
                sendPhoneCode(this.user.phoneNumber).then(() => {
                  this.doBtnControl()
                })
              } else if (this.type === "email") {
                sendEmailCode(this.user.email).then(() => {
                  this.doBtnControl()
                })
              }
            } else {
              this.passError = true
            }
          })
        }
      })
    },
    // 表单重置
    reset() {
      this.passError = false
      this.codeError = false
      this.verifyVisible = false
      this.resetForm("changeForm")
    },
    netxtStep() {
      this.$refs["changeForm"].validateField("authCode", (err) => {
        if (!err) {
          let codeType = this.type === "phone" ? "CodePhone" : "CodeEmail"
          checkCode({
            phoneNumber: this.user.phoneNumber,
            email: this.user.email,
            code: this.changeForm.authCode,
            type: codeType,
          }).then((res) => {
            if (res.data) {
              let type = this.type
              this.reset()
              this.$emit("update", type)
            } else {
              this.codeError = true
            }
          })
        }
      })
    },
    doBtnControl() {
      this.validateCodeBtn = true
      this.$modal.msgSuccess("验证码发送成功，5分钟内有效")
      let count = 60
      let timer = setInterval(() => {
        count--
        this.validateCodeBtnText = count + "s后重新发送"
        if (count == 0) {
          if (this.type === "phone") {
            this.validateCodeBtnText = "发送短信验证码"
          } else if (this.type === "email") {
            this.validateCodeBtnText = "发送邮箱验证码"
          }
          this.validateCodeBtn = false
          clearInterval(timer)
        }
      }, 1000)
    },
  },
}
</script>

<style lang="scss" scoped>
.info-form {
  .el-input--medium {
    width: 25%;
  }
  .change-btn {
    margin-left: 10px;
  }
}

.dialog-title {
  color: #40485b;
  width: 100%;
  border-bottom: 1px solid #eee;
  position: absolute;
  left: 0;
  top: 0;
  padding: 15px;
  font-size: 1.143rem;
  font-weight: bold;
}

.change-form {
  .form-item-label {
    color: rgba(0, 0, 0, 0.8);
    font-size: 1em;
    font-weight: bold;
  }
  .red-color {
    color: #d95c5c;
  }
}

.send-btn {
  color: #fe7300 !important;
}
.mobile {
  color: #333;
}
</style>
